using MultiAgentsServer.Scripts.Shared.enums;
using MultiAgentsShared;
using static MultiAgentsClient.Manager.UserInfoManager;
using static MultiAgentsClient.Presentation.SettingsMainAreaModel;

namespace MultiAgentsClient.Presentation;

public partial record ChangePasswordPopupModel
{
    private readonly IEventBus eventBus;

    public IState<string> PreviousPassword => State.Value(this, () => "");
    public IState<string> NewPassword => State.Value(this, () => "");
    public IState<string> NewPasswordEnsure => State.Value(this, () => "");
    public IState<bool> IsPopupOpen => State.Value(this, () => false);

    public ChangePasswordPopupModel()
    {
        eventBus = EventBus.Instance;

        eventBus.Subscribe<ChangePasswordButtonClickCommand>(async cmd => { await ChangePasswordButtonClickCommandHandler(); });
        eventBus.Subscribe<ChangePasswordCompletedCommand>(async cmd => { await ChangePasswordCompletedCommandHandler(cmd); });
    }

    public async ValueTask CreateProject()
    {
        string? previousPassword = await PreviousPassword;
        string? newPassword = await NewPassword;
        string? newPasswordEnsure = await NewPasswordEnsure;
        if (string.IsNullOrEmpty(previousPassword) || string.IsNullOrEmpty(newPassword))
        {
            Debug.LogWindow("密码不可为空");
            return;
        }
        else if (newPassword != newPasswordEnsure)
        {
            Debug.LogWindow("两次密码输入不一致");
            return;
        }

        eventBus.Publish(new ChangePasswordCommand(previousPassword, newPassword));
    }

    public async ValueTask Close()
    {
        await IsPopupOpen.SetAsync(false);
    }

    private async ValueTask ChangePasswordButtonClickCommandHandler()
    {
        await IsPopupOpen.SetAsync(true);
    }

    private async ValueTask ChangePasswordCompletedCommandHandler(ChangePasswordCompletedCommand cmd)
    {
        switch (cmd.Status)
        {
            case StatusCode.Status200:
                Debug.LogWindow("修改成功。");
                await IsPopupOpen.SetAsync(false);
                break;
            case StatusCode.Status4006:
                Debug.LogWindow("身份验证失败，请重新尝试。");
                break;
            default:
                Debug.LogWindow("修改失败，未知错误，请联系管理员。");
                break;
        }
    }
}
